home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 6532 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: Thomas.generics.co.uk!usenet
  2. From: Rob Stenton <rws@metagen.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: accessing structures (newbie question)
  5. Date: Mon, 19 Feb 1996 14:32:00 -0800
  6. Organization: MediaWell Ltd.
  7. Message-ID: <3128FA60.5227@metagen.co.uk>
  8. References: <4g8gic$o6u@news1.sunbelt.net>
  9. NNTP-Posting-Host: 194.216.45.117
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0b6b (Win16; I)
  14.  
  15. dking@SunBelt.Net wrote:
  16. > Ok. having trouble accessing structure.
  17.  
  18. There are basically two ways of accessing elements within a malloced 
  19. buffer:
  20. 1. Treat the malloced buffer as an array (as you suggested).
  21. 2. Increment a local pointer by sizeof(picture) in loop iteration.
  22.  
  23. The first method is preferable because the second method involves pointer 
  24. arithmetic (always best avoided) which can cause problems on different 
  25. memory architectures and assumes things about BYTE sizes (but usually 
  26. works).
  27.  
  28. I think you may have been using the wrong syntax when you tried the array 
  29. method. The xth item is given by 'photos[x].' which is equivalent to 
  30. '(photos + x * sizeof(picture))->'.
  31.  
  32. The two ways for solving this problem are therefore:
  33. 1. (Recommended)
  34.          for (x=0;x<num_of_files;x++)
  35.          {
  36.                  strncpy(photos[x].filename, filelist[x],12);
  37.                  strncpy(photos[x].diskname, inputdisk,12);
  38.                  strncpy(photos[x].indexname, inputindex,12);
  39.          }
  40. or
  41. 2. (Not recommended)
  42.          for (x=0;x<num_of_files;x++)
  43.          {
  44.                  strncpy((photos + x * sizeof(picture))->filename, 
  45. filelist[x],12);
  46.                  strncpy((photos + x * sizeof(picture))->diskname, 
  47. inputdisk,12);
  48.                  strncpy((photos + x * sizeof(picture))->indexname, 
  49. inputindex,12);
  50.          }
  51.  
  52. Perhaps you were confusing the use of '.' and '->' when you tried this 
  53. yourself. If you understand the use of '.' and '->' in the above 
  54. solutions I think you will have this licked !
  55. Rob
  56.